package com.ewhale.feitengguest.ui.shop.mine

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.ArticleDetailDto
import com.ewhale.feitengguest.dto.LoginInfoDto
import com.ewhale.feitengguest.presenter.shop.mine.ShopRechargePresenter
import com.ewhale.feitengguest.ui.WebViewActivity
import com.ewhale.feitengguest.utils.PictureUtils
import com.ewhale.feitengguest.utils.QiniuUtils
import com.ewhale.feitengguest.view.shop.mine.ShopRechargeView
import com.luck.picture.lib.PictureSelector
import com.orhanobut.hawk.Hawk
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.HawkKey
import com.simga.library.utils.glide.GlideUtil
import com.simga.library.widget.SelectPhotoDialog
import kotlinx.android.synthetic.main.activity_shop_recharge.*
import kotlinx.android.synthetic.main.activity_shop_recharge.btn_commit
import kotlinx.android.synthetic.main.activity_shop_recharge.et_inputAmount
import kotlinx.android.synthetic.main.activity_shop_with_draw.*
import kotlinx.android.synthetic.main.activity_shop_with_draw.radioGroup
import kotlinx.android.synthetic.main.activity_shop_with_draw.tv_2
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal
import java.util.ArrayList

class ShopWithDrawActivity : MBaseActivity<ShopRechargePresenter>(), ShopRechargeView, EasyPermissions.PermissionCallbacks {
    override fun goToThirdPay(info: Any) {}

    override fun getViewId(): Int {
        return R.layout.activity_shop_with_draw
    }
    override fun isUseBaseTitleBar(): Boolean {
        return true
    }
    private var payType = 2 //2支付宝1微信
    private val mPhotoDialog by lazy(LazyThreadSafetyMode.NONE) { SelectPhotoDialog(mContext) }
    private var chooseType = 1
    private var wechatImage = ""
    private var amount = BigDecimal(0)
    override fun onGetBundle(bundle: Bundle?) {
        super.onGetBundle(bundle)
        amount = bundle!!.getSerializable("amount") as BigDecimal
    }

    override fun init(savedInstanceState: Bundle?) {
        setTitle("提现")
        tv_all_amount.text = "可提现余额${amount.stripTrailingZeros().toPlainString()}元"
    }

    override fun withSuccess() {
        showToast("提现成功，请等待后台审核处理")
        finishResult()
    }

    override fun initListener() {
        super.initListener()
        tv_2.setOnClickListener {
            presenter.loadArticleDetails(15)
        }
        iv_deleteImage.setOnClickListener {
            wechatImage = ""
            iv_deleteImage.visibility = View.GONE
        }
        tv_all.setOnClickListener {
            et_inputAmount.setText(amount.stripTrailingZeros().toPlainString())
            if(et_inputAmount.text.isNotEmpty()){
                et_inputAmount.setSelection(et_inputAmount.text.toString().length)
            }
        }
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_alipay -> {
                    payType = 2
                    ll_aliPay.visibility = View.VISIBLE
                    ll_weChatImg.visibility = View.GONE
                }
                R.id.rb_wechat -> {
                    payType = 1
                    ll_aliPay.visibility = View.GONE
                    ll_weChatImg.visibility = View.VISIBLE
                }
            }
        }
        iv_wechatCode.setOnClickListener {
            mPhotoDialog.setOnClickItem(object : SelectPhotoDialog.onClickItem {
                override fun onOneClick() {
                    chooseType = 1
                    requestPermissionsMain()
                }
                override fun onTwoClick() {
                    chooseType = 2
                    requestPermissionsMain()
                }
            })
            mPhotoDialog.show()
        }
        btn_commit.setOnClickListener {
            var amount = et_inputAmount.text.toString()
            if(amount.isEmpty()){
                showToast("请输入提现金额")
                return@setOnClickListener
            }
            if(amount.isNotEmpty()){
                if(amount.substring(0,1) == "."){
                    amount = "0$amount"
                }
            }
            if(ShopWithDrawActivity@this.amount.compareTo(BigDecimal(0)) == 0||amount.toBigDecimal().compareTo(ShopWithDrawActivity@this.amount) == 1){
                showToast("当前余额不足")
                return@setOnClickListener
            }
            if (amount.isEmpty()) {
                showToast("请输入提现金额")
                return@setOnClickListener
            }
            if (amount.toBigDecimal().compareTo(BigDecimal(0)) == 0) {
                showToast("提现金额不能必须大于0")
                return@setOnClickListener
            }
            if (payType == 1) {
                if (wechatImage.isEmpty()) {
                    showToast("请上传微信收款码")
                    return@setOnClickListener
                }
            } else {
                if (et_inputRealName.text.isEmpty()) {
                    showToast("请填写支付宝收款人真实姓名")
                    return@setOnClickListener
                }
                if (et_inputAccount.text.isEmpty()) {
                    showToast("请填写支付宝收款人账号")
                    return@setOnClickListener
                }
            }
            val params = HashMap<String, Any>()
            params["amount"] = amount
            params["type"] = payType
            if (payType == 1) {
                params["wechatImg"] = wechatImage
            } else {
                params["aliAccount"] = et_inputAccount.text.toString()
                params["trueName"] = et_inputRealName.text.toString()
            }
            presenter.withDraw(params)
        }
    }


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_2)
    private fun requestPermissionsMain() {
        val perms = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
        if (EasyPermissions.hasPermissions(mContext, *perms)) {
            if (chooseType == 1) {
                PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
            } else {
                PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
            }
        } else {
            EasyPermissions.requestPermissions(this, "申请获取相关权限",
                    REQUEST_CODE_PERMISSION_2, *perms)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        if (chooseType == 1) {
            PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
        } else {
            PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).setTitle("权限申请")
                    .setRationale("申请获取相关权限")
                    .setPositiveButton(getString(R.string.comfir))
                    .setNegativeButton(getString(R.string.cancle))
                    .build()
                    .show()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == REQUEST_CODE_CHOOSE_COMMENT_IMAGE) {
            val images = ArrayList<String>()
            images.add(PictureSelector.obtainMultipleResult(data)[0].cutPath)
            QiniuUtils.uploadImage(images) { keys ->
                wechatImage = keys[0]
                GlideUtil.loadPicture(wechatImage,iv_wechatCode)
                iv_deleteImage.visibility = View.VISIBLE
                PictureUtils.clearCache(mContext)
            }
        }
    }

    override fun showDetail(result: ArticleDetailDto) {
        WebViewActivity.open(mContext, "提现协议", result.content)
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String?, message: String?) {
        showErrorMsg(code, message)
    }

    companion object {
        const val REQUEST_CODE_PERMISSION_2 = 10002
        const val REQUEST_CODE_CHOOSE_COMMENT_IMAGE = 1000
        fun open(mContext: MBaseActivity<*>, amount: BigDecimal) {
            val bundle = Bundle()
            bundle.putSerializable("amount", amount)
            mContext.startForResult(bundle, 10001, ShopWithDrawActivity::class.java)
        }
    }
}
